<route lang="json5">
{
  style: {
    navigationStyle: 'custom',
  },
}
</route>

<template>
  <view class="publish">
    <!-- 顶部导航栏 -->
    <wd-navbar safeAreaInsetTop :title="state.title" left-arrow @click-left="handleClickLeft">
      <template #right>
        <wd-button size="small" @click="handlePublish">发布</wd-button>
      </template>
    </wd-navbar>
    <!-- 色块 -->
    <view class="h-20rpx bg-[#F5F5F5]"></view>
    <!-- 发布内容 -->
    <wd-textarea v-model="state.content" placeholder="请输入文字" clearable />
    <!-- TODO：校验提示 -->
    <view v-if="state.hasContent" class="text-[#FA4350] text-24rpx indent-30rpx">请输入内容</view>
    <!-- 选中主题 -->
    <view
      class="chooseTheme"
      v-if="state.selectedThemeName"
      :style="{
        width: `${themeNameWidth('#' + state.selectedThemeName + 'x')}`,
      }"
    >
      <text>#{{ state.selectedThemeName }}</text>
      <wd-icon
        name="close"
        size="22rpx"
        class="ml-12rpx"
        color="#3670F7"
        @click="handleDelTheme"
      ></wd-icon>
    </view>
    <!-- 主题 -->
    <view class="theme">
      <text
        v-for="(item, index) in state.hotThemeList"
        :key="item.topicId"
        @click="handleChooseTheme(item, index)"
        :style="{
          width: `${themeNameWidth(item.topicName)}`,
          maxWidth: '180rpx',
        }"
      >
        #{{ item.topicName }}
      </text>
    </view>
    <!-- TODO：校验提示 -->
    <!-- <view v-if="state.hasTheme" class="text-[#FA4350] text-24rpx indent-30rpx hasTheme">
      请选择主题
    </view> -->
    <!-- 上传图片框 -->
    <view v-if="state.title === '图文'" class="upload">
      <wd-upload
        v-model:file-list="state.fileList"
        :limit="9"
        multiple
        action="/resource/oss/upload"
      ></wd-upload>
    </view>
    <!-- TODO：校验提示 -->
    <view
      v-if="state.hasImage && state.title === '图文'"
      class="text-[#FA4350] text-24rpx indent-30rpx"
    >
      请上传图片
    </view>
    <!-- 点击选择主题 - 弹出层 -->
    <wd-popup
      v-model="state.chooseThemePopupShowYn"
      position="bottom"
      custom-style="height: 90vh"
      @close="state.chooseThemePopupShowYn = false"
    >
      <!-- 标题 -->
      <view class="text-center fw-700 text-[#3d3d3d] text-32rpx mt-20rpx mb-30rpx">添加主题</view>
      <!-- 输入框 -->
      <view class="w-94% box-border flex items-center theme-input-border">
        <text class="w-20rpx mr-16rpx text-[#3d3d3d] fw-700 text-32rpx">#</text>
        <wd-input
          v-model="state.newTheme"
          :maxlength="30"
          show-word-limit
          @input="getFilterThemeList"
          placeholder="请创建或选择主题"
          class="flex-1 theme-input"
        />
      </view>
      <!-- 主题列表 -->
      <view v-if="state.filterThemeList.length > 0" class="theme-list">
        <view
          v-for="item in state.filterThemeList"
          :key="item.topicId"
          @click="handleChooseTheme(item)"
        >
          <view class="theme-item">
            <view v-if="!state.newThemeFlag">
              <view>
                <text class="symbol">#</text>
                <text>{{ item.topicName }}</text>
              </view>
              <text>{{ formatViews(item.quoteCount || 0) }} 参与</text>
            </view>
            <view v-else @click.stop="handleAddTheme">
              <view>
                <text class="symbol">#</text>
                <text>{{ state.newTheme }}</text>
              </view>
              <text>创建新主题</text>
            </view>
          </view>
        </view>
      </view>
      <view v-else class="empty-state flex-center flex-col mt-200rpx">
        <wd-status-tip :image="emptyImage" tip="暂无主题" />
      </view>
    </wd-popup>
  </view>
</template>

<script setup lang="ts">
import { useUserStore } from '@/store'
import { addDiscussionData, getThemeApi, addThemeApi, getUserAddress } from '@/service/edu/comment'
/* 引入 暂无数据 - 图片 */
import emptyImage from '@/static/images/icons/empty.png'

/* 定义数据 */
const state = reactive<{
  page: string
  title: string
  content: string
  themeList: any[]
  hotThemeList: any[]
  filterThemeList: any[]
  fileList: any[]
  chooseThemePopupShowYn: boolean
  newTheme: string
  newThemeFlag: boolean
  selectedThemeName: string
  selectedThemeId: number | string
  longitude: string
  latitude: string
  hasContent: boolean
  // hasTheme: boolean
  hasImage: boolean
}>({
  /* 当前页面/组件 */
  page: 'details',
  /* 导航栏标题 */
  title: '',
  /* 发布内容 */
  content: '',
  /* 主题列表 */
  themeList: [],
  /* 热门主题列表 */
  hotThemeList: [],
  /* 筛选主题列表 */
  filterThemeList: [],
  /* 图片列表 */
  fileList: [],
  /* 选择主题 - 弹出层 */
  chooseThemePopupShowYn: false,
  /* 即将添加的主题 */
  newTheme: '',
  /* 判断是否创建新主题 */
  newThemeFlag: false,
  /* 选中的主题 */
  selectedThemeName: '',
  selectedThemeId: '',
  /* 经纬度 */
  longitude: '',
  latitude: '',
  /* 校验提示 */
  hasContent: false,
  // hasTheme: false,
  hasImage: false,
})

/* 获取热门主题 */
async function getHotThemeList() {
  const res: any = await getThemeApi({
    topicName: '',
  })
  console.log('[ getThemeApi ] 🌸>', res)
  if (res?.code === 200) {
    state.hotThemeList = res?.rows.slice(0, 2) || []
    // state.filterThemeList = cloneDeep(res?.rows)
    state.hotThemeList.unshift({ topicName: '选择主题' })
  }
}

/* 查询主题 */
async function getFilterThemeList() {
  const res: any = await getThemeApi({
    topicName: state.newTheme.trim(),
  })
  console.log('[ getThemeApi ] ���>', res)
  if (res?.code === 200) {
    state.filterThemeList = res?.rows || []
    if (state.filterThemeList.length === 0) {
      state.newThemeFlag = true
      state.filterThemeList = [
        {
          topicId: +new Date(),
          topicName: state.newTheme,
        },
      ]
    } else {
      state.newThemeFlag = false
    }
  }
}

/* 控制主题的展示 */
function themeNameWidth(themeName) {
  let num = 0
  for (const char of themeName) {
    if (/[a-zA-Z0-9]/.test(char)) {
      num += 14
    } else {
      num += 25
    }
  }
  return `${num + 32}rpx`
}

/* 选择主题 */
async function handleChooseTheme(item: any, index?: number) {
  /* 重置一下 */
  state.newTheme = ''
  if (index === 0 && item.topicName === '选择主题') {
    state.chooseThemePopupShowYn = true
    await getFilterThemeList()
  } else {
    console.log('[ item.topicName ] 🌸>', item.topicName)
    state.selectedThemeName = item.topicName
    state.selectedThemeId = item.topicId
    state.chooseThemePopupShowYn = false
  }
}

/* 创建新主题 */
async function handleAddTheme() {
  try {
    await addThemeApi({
      topicName: state.newTheme.trim(),
    })
  } catch (e) {
    console.error('添加主题失败')
  } finally {
    state.chooseThemePopupShowYn = false
    state.newThemeFlag = false
  }
}

/* 删除主题 */
function handleDelTheme() {
  state.selectedThemeName = ''
  state.selectedThemeId = ''
}

uni.getLocation({
  type: 'wgs84',
  success: function (res) {
    state.longitude = `${res.longitude}` || ''
    state.latitude = `${res.latitude}` || ''
    console.log('当前位置的经度：' + res.longitude)
    console.log('当前位置的纬度：' + res.latitude)
  },
})

/* 有无内容 */
watch(
  () => state.content,
  (newVal, oldVal) => {
    state.hasContent = !newVal
  },
)

/* 有无主题 */
// watch(
//   () => state.selectedThemeName,
//   (newVal, oldVal) => {
//     state.hasTheme = !newVal
//   },
// )

/* 有无主题 */
watch(
  () => state.fileList,
  (newVal, oldVal) => {
    state.hasImage = !newVal.length
  },
  { deep: true },
)

/* 发布 */
const userStore = useUserStore()
async function handlePublish() {
  console.log('[ state.fileList ] 🌸>', state.fileList)
  const picture = state.fileList.map((e) => JSON.parse(e.response).data.url).join(',') ?? ''
  /* 获取地理定位通过经纬度 */
  const res: any = await getUserAddress({
    longitude: state.longitude,
    latitude: state.latitude,
  })
  const address = res ? res.regeocode.addressComponent.province : ''
  console.log('[ res ] 🌸>', res.regeocode.addressComponent.province)
  if (!state.content) {
    state.hasContent = true
  }
  // if (!state.selectedThemeName) {
  //   state.hasTheme = true
  // }
  if (!picture && state.title === '图文') {
    state.hasImage = true
  }
  if (state.hasContent || state.hasImage) {
    return
  }
  try {
    await addDiscussionData({
      content: state.content,
      picture,
      // address,
      userId: userStore.userInfo?.userId,
      topicId: state.selectedThemeId,
      topicName: state.selectedThemeName,
    })
  } catch (e) {
    console.error('发布失败')
  } finally {
    uni.navigateBack()
  }
}

function formatViews(views) {
  if (views >= 1e8) {
    // 过亿
    return (views / 1e8).toFixed(1) + '亿' // 保留一位小数
  } else if (views >= 1e4) {
    // 过万
    return (views / 1e4).toFixed(1) + '万' // 保留一位小数
  } else {
    return views.toString() // 小于万的直接返回
  }
}

/* 顶部导航栏 - 返回 */
function handleClickLeft() {
  uni.navigateBack()
}

onLoad(async (query) => {
  const { title } = query
  state.title = title
  /* 在主题数组头部添加 1 条数据，选择主题 */
  await getHotThemeList()
})
</script>

<style lang="scss" scoped>
.publish {
  position: relative;
  min-height: 100vh;
  background: #fff;
  /* 导航栏 - 发布按钮 */
  .wd-button.is-small {
    width: 100rpx;
    border-radius: 12rpx !important;
  }
  /* 发布内容 */
  /* stylelint-disable-next-line selector-type-no-unknown */
  :deep(uni-textarea) {
    height: 300rpx;
  }
  /* 主题 */
  .theme {
    margin-top: 12rpx;
    margin-left: 30rpx;
    & > text {
      display: inline-block;
      padding: 4rpx 20rpx;
      margin-right: 12rpx;
      overflow: hidden;
      font-size: 26rpx;
      color: #767c89;
      text-overflow: ellipsis;
      white-space: nowrap;
      background-color: #d9d9d9;
      border-radius: 20rpx;
    }
  }
  /* 选中主题 */
  .chooseTheme {
    display: flex;
    align-items: center;
    padding: 0 12rpx 0 20rpx;
    margin-top: 12rpx;
    margin-left: 30rpx;
    border: solid 1rpx #3670f7;
    border-radius: 10rpx;
    /* stylelint-disable-next-line no-descending-specificity */
    text {
      display: inline-block;
      overflow: hidden;
      font-size: 26rpx;
      color: #3670f7;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
  /* 请选择主题 提示语 */
  // .hasTheme {
  //   position: absolute;
  //   top: 600rpx;
  // }
  /* 输入框 - 添加下边框线 */
  .theme-input-border {
    margin: 0 auto 20rpx;
    border-bottom: solid 1rpx #e6e6e6;
  }
  /* 添加主题 - 输入框 */
  :deep(.theme-input)::after {
    display: none;
  }
  /* 添加主题 - 主题列表 */
  .theme-list {
    line-height: 2.5;
    & > view {
      padding: 0 20rpx;

      .theme-item {
        & > view {
          display: flex;
          align-items: center;
          justify-content: space-between;
          & > view:nth-child(1) {
            display: flex;
            align-items: center;
            width: 80%;
          }
          .symbol {
            display: inline-block;
            width: 50rpx;
            height: 50rpx;
            margin-right: 20rpx;
            font-size: 32rpx;
            font-weight: 700;
            line-height: 50rpx;
            color: #3d3d3d;
            text-align: center;
            border: solid 1rpx #cccccc;
            border-radius: 10rpx;
          }
          .symbol ~ text {
            display: inline-block;
            width: calc(100% - 50rpx);
            overflow: hidden;
            font-size: 30rpx;
            color: #333333;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
          /* stylelint-disable-next-line no-descending-specificity */
          & > text {
            font-size: 22rpx;
            color: #999999;
            white-space: nowrap;
          }
        }
      }
    }
  }
  /* 上传图片框 */
  .upload {
    :deep(.wd-upload) {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 8rpx 6rpx;
      padding: 20rpx 30rpx;
    }

    :deep(.wd-upload__preview),
    :deep(.wd-upload__evoke) {
      width: 100%;
      height: 100%;
      aspect-ratio: 1 / 1;
      margin: 0;
    }
  }
}
</style>
